import ApiClient from './ApiClient';
import { AccessTokenKey, OpenidKey, UnionidKey } from '../config';

const appid = 1;
export default {
    getUserInfo() {
        return new Promise((resolve, reject) => {
            ApiClient.get('/user/info').then(response => {
                resolve(response.result);
            }).catch(reason => {
                reject(reason);
            });
        });
    },
    updateSession() {
        return new Promise((resolve, reject) => {
            //重新登录
            wx.login({
                success: result => {
                    const code = result.code;
                    ApiClient.post('/user/miniprogram/session', { code, appid }).then(response => {
                        const { openid, unionid, access_token } = response.result;
                        if (openid) wx.setStorageSync(OpenidKey, openid);
                        if (unionid) wx.setStorageSync(UnionidKey, unionid);
                        if (access_token) {
                            wx.setStorageSync(AccessTokenKey, access_token);
                            resolve(response.result);
                        } else {
                            reject(response);
                        }
                    }).catch(reason => {
                        reject(reason);
                    });
                },
                fail: res => {
                    reject(res);
                }
            });
        });
    },
    register(data) {
        // avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/tNHYbW9g7BYLLU7CoGMLvhdZQar2UaksG2I5VekibHX71XucIcDtb0Vib3CJkPbRaMwBO3DMEZXDAKUW10szqu1w/132"
        // city: "Liupanshui"
        // country: "China"
        // gender: 1
        // language: "zh_CN"
        // nickName: "贵州大师兄"
        // province: "Guizhou"
        return new Promise((resolve, reject) => {
            try {
                ApiClient.post('/user/miniprogram/register', data).then(response => {
                    const { access_token } = response.result;
                    if (access_token) {
                        wx.setStorageSync(AccessTokenKey, access_token);
                        resolve(response.result);
                    } else {
                        reject(response);
                    }
                });
            } catch (e) {
                reject();
            }
        });
    }
};
